package com.cloudcross.ssp.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class TokenUtil {
	
	public static String getToken(){
		String ret = "";
		try {
			String secret = getRandomString(24);
			// 24字节密钥key,3倍DES密钥长度
			byte[] tripleKey = getKeyBytes(secret);
			// 生成密钥 
			SecretKey secretKey = new SecretKeySpec(tripleKey, "DESede");
			String transformation = "DESede/CBC/PKCS5Padding";
			Cipher cipher = Cipher.getInstance(transformation);     
			// CBC方式的初始化向量 
	   		byte[] iv = new byte[] { 93, 81, 122, 33, 47, 50, 17, 103 };    
			IvParameterSpec ivparam = new IvParameterSpec(iv);     
			// 加密 
	   		cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivparam);    
			// 当前时间字符串
			String currentTime = System.currentTimeMillis()+"";
			byte[] encriptText = cipher.doFinal(currentTime.getBytes());
			// Hash算法 
	   		MessageDigest sha = MessageDigest.getInstance("SHA-1");    
			sha.update(encriptText);
			// 返回其 16 进制字符串
			ret = bytesToHexString(sha.digest());
		} catch (Exception e) {
			System.out.print(e.getMessage());
		} 
		return ret;
	}
		
	
	/**
	 * 获取随机的字符串
	 * @param length 字符串长度
	 * @return
	 */
	public static String getRandomString(int length){
		String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
	    Random random = new Random();  
	    StringBuffer sb = new StringBuffer();  
	    for(int i = 0 ; i < length; ++i){  
	    	int number = random.nextInt(62);//[0,62)  
	        sb.append(str.charAt(number));  
	    }
	    return sb.toString();
	}
	
	/**   
	 * 检查密钥长度,如不足24位,则加0x00补齐   
	 *    
	 * @param keyString   
	 * @return   
	 */
	public static byte[] getKeyBytes(String keyString){
		byte[] b = new byte[24];
		byte[] key = keyString.getBytes();
	   	int count = keyString.getBytes().length;
	   	for (int i = 0; i < count; i++) {
			b[i] = key[i];   
		}   
		for (int i = count; i < 24; i++) {
			b[i] = 0x20;   
		}
		return b;
	}
	
	/** 
	 * 把字节数组转换成16进制字符串
	 * 
	 * @param bArray
	 * @return
	 */
	public static String bytesToHexString(byte[] bArray) {
		StringBuffer sb = new StringBuffer(bArray.length);
		String sTemp;
		for (int i = 0; i < bArray.length; i++) {  
			sTemp = Integer.toHexString(0xFF & bArray[i]);
			if (sTemp.length() < 2)	sb.append(0);
			sb.append(sTemp.toUpperCase());
		}
		return sb.toString();
	}
	
	/**
     * 生成token md5加密
     * 
     * @param publickey+dspId+signTime
     * @return String
     */
    public static String getMd5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密  
            return buf.toString();
            // 16位的加密  
            //return buf.toString().substring(8, 24);  
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
	
	public static void main(String[] args) {
		System.err.println(getToken());
	}
}
